package first.web;



import first.utils.UploadUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * 项目名称：File
 * 类 名 称：${NAME}
 * 类 描 述：TODO
 * 创建时间：2019-12-02 10:48
 * 创 建 人：jacksonmike
 */
@WebServlet(name = "ServletDownload", value = "/download")
public class ServletDownload extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String uuidFileName = request.getParameter("filename");
        String basePath = this.getServletContext().getRealPath("/WEB-INF/upload");
        if (uuidFileName!=null&&uuidFileName.trim().length()!=0){
            //文件名
            String filename = uuidFileName.substring(uuidFileName.indexOf("_") + 1);
            String newPath = UploadUtils.createNewPath(basePath, filename);
            File file = new File(newPath + "/" + uuidFileName);
            if (file.exists()){
                ServletOutputStream os = response.getOutputStream();
                response.setHeader("content-disposition",
                        "attachment;filename="+ URLEncoder.encode(filename, "utf-8"));
                FileInputStream fis = new FileInputStream(file);
                byte[] buf = new byte[1024*4];
                int len = -1;
                while ((len=fis.read(buf))!=-1){
                    os.write(buf, 0, len);
                }
            }else {
                response.setContentType("text/html;charset=utf-8");
                response.getWriter().write("文件已经删除了");
            }
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
